import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.time.LocalDateTime;

public final class Server {
  private Server() {}

  public static void main(String args[]) throws IOException {
    String path = args[0];
    int port = args.length > 1 ? Integer.valueOf(args[1]) : 8000;

    HttpServer server = HttpServer.create(new InetSocketAddress("0.0.0.0", port), 0);
    server.createContext("/", new Handler(path));
    System.out.println("Serving " + path + " on port " + port);
    server.start();
  }

  private static class Handler implements HttpHandler {
    private final String path;

    public Handler(String path) {
      this.path = path;
    }

    public void handle(HttpExchange exchange) throws IOException {
      System.out.println("Access: " + LocalDateTime.now().toString());
      byte[] data = Files.readAllBytes(Paths.get(path));
      exchange.sendResponseHeaders(200, data.length);
      try (OutputStream os = exchange.getResponseBody()) {
        os.write(data);
        os.flush();
      }
    }
  }
}
